<template>
  <div>
    <BasicCard title="报价规则" class="page-container">
      <template #operator>
        <div class="actions">
          <z-button size="small" @click="handleImport">导入报价</z-button>
          <z-button class="z-icon-download" size="small" @click="handleExport">导出报价</z-button>
        </div>
      </template>
      <template #body>
        <!-- 快捷设置 -->
        <quickForm
          ref="quickFormRef"
          :destinationAreaGroup="tableData"
          :weightGroup="dynamicColumns"
          :formData="formData"
          @batchUpdate="handleBatchUpdate"
        ></quickForm>
        <!-- 操作费按票收费的时候展示 -->
        <div v-if="formData.subCostType === feeTypeEnum.operate && formData.quoteMode === '0'" class="package-mode">
          包内件收费模式：<z-radio-group v-model="tempQuoteMode">
            <z-radio label="8">整包收费</z-radio>
            <z-radio label="0">逐票收费</z-radio>
          </z-radio-group>
        </div>
        <z-table ref="tableRef" :key="tableKey" :data.sync="tableData" border :max-height="500">
          <z-table-column
            v-for="item in tableColumns"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            :fixed="item.fixed || false"
            :min-width="item.minWidth"
            :show-overflow-tooltip="false"
          >
            <template slot-scope="{ row, $index }">
              <div v-if="item.prop === 'destinationAreaGroup'" class="area-box">
                <span class="group-name">
                  {{ row.destinationAreaGroup }}
                </span>
                <div class="area-list">
                  <div v-for="area in row.areaList" :key="area.value" class="desination" type="info">
                    <!-- {{ row.areaList.map(item => item.label).join(',') }} -->
                    {{ area.label }}
                  </div>
                  <i
                    v-if="isLastRow($index)"
                    class="z-icon-circle-plus-outline"
                    @click="handleAddAreaGroup($index)"
                  ></i>
                  <i class="z-icon-edit" @click="handleEditAreaGroup($index)"></i>
                  <i v-if="$index !== 0" class="z-icon-delete" size="16" @click="handleDeleteAreaGroup($index)"></i>
                </div>
              </div>
            </template>
          </z-table-column>
          <z-table-column
            v-for="(item, colIndex) in dynamicColumns"
            :key="`weight${item.weightKey}`"
            label="重量段"
            :prop="`weight${item.weightKey}`"
            :min-width="getMinWidth(item)"
          >
            <template #header>
              <div class="header-box">
                <span>{{ item.startWeight }} </span>
                <!-- <z-input-number
                  v-else
                  v-model="item.startWeight"
                  disabled
                  :controls="false"
                  :min="minWeight"
                  :max="MAX_WEIGHT"
                  :precision="2"
                  style="width: 100px"
                ></z-input-number> -->
                ＜重量≤
                <z-input-number
                  v-if="colIndex === dynamicColumns.length - 1"
                  v-model="item.endWeight"
                  :controls="false"
                  :min="getColMinValue(item, colIndex)"
                  :max="MAX_WEIGHT"
                  :precision="2"
                  style="width: 100px"
                  @blur="handleWeightBlur(item)"
                ></z-input-number>
                <span v-else>{{ item.endWeight }}</span>
                <!-- <z-tooltip effect="dark" content="拆分重量段" placement="top">
                  <i class="z-icon-c-scale-to-original" @click="handleScaleToOriginal(item)"></i>
                </z-tooltip> -->
                <z-tooltip effect="dark" content="删除" placement="top">
                  <i v-if="dynamicColumns.length !== 1" class="z-icon-delete" size="16" @click="handleDelete(item)"></i>
                </z-tooltip>
              </div>
            </template>
            <template slot-scope="{ row }">
              <div class="flex-box">
                <z-select
                  v-model="row[`formulaType${item.weightKey}`]"
                  :disabled="formulaTypeOpts.length === 1"
                  :style="{ width: row[`formulaType${item.weightKey}`] === '3' ? '460px' : 'fit-content' }"
                  style="width: 100%"
                >
                  <z-option
                    v-for="el in formulaTypeOpts"
                    :key="el.value"
                    :label="el.label"
                    :value="el.value"
                  ></z-option>
                </z-select>
                <div class="flex-box__item">
                  <div v-if="['1'].includes(row[`formulaType${item.weightKey}`])">
                    <z-input-number
                      v-model="row[`formula0${item.weightKey}`]"
                      :controls="false"
                      :min="0"
                      :precision="3"
                      :max="MAX_PRICE"
                      placeholder="请输入"
                      style="margin-right:4px;width: 100px;"
                    ></z-input-number
                    >元/票
                  </div>
                  <div v-if="['2'].includes(row[`formulaType${item.weightKey}`])">
                    <z-input-number
                      v-model="row[`formula1${item.weightKey}`]"
                      :controls="false"
                      :min="0"
                      :max="MAX_WEIGHT"
                      :precision="2"
                      placeholder="请输入"
                      style="margin-right:4px;width: 100px;"
                    ></z-input-number
                    >元/kg
                  </div>
                  <div v-if="['3'].includes(row[`formulaType${item.weightKey}`])">
                    <z-input-number
                      v-model="row[`formula2${item.weightKey}`]"
                      :controls="false"
                      :min="0"
                      :precision="3"
                      :max="MAX_PRICE"
                      placeholder="请输入"
                      style="margin-right:4px;width: 70px;"
                    ></z-input-number>
                    元/票 +（结算重量 -
                    <z-input-number
                      v-model="row[`formula3${item.weightKey}`]"
                      :controls="false"
                      :min="0"
                      :max="MAX_WEIGHT"
                      :precision="2"
                      placeholder="请输入"
                      style="margin-right:4px;width: 70px;"
                    ></z-input-number
                    >kg）*
                    <z-input-number
                      v-model="row[`formula4${item.weightKey}`]"
                      :controls="false"
                      :min="0"
                      :max="MAX_WEIGHT"
                      :precision="2"
                      placeholder="请输入"
                      style="margin-right:4px;width:70px;"
                    ></z-input-number
                    >元/kg
                  </div>
                  <div v-if="['4'].includes(row[`formulaType${item.weightKey}`])">
                    <z-input-number
                      v-model="row[`formula0${item.weightKey}`]"
                      :controls="false"
                      :min="0"
                      :precision="getMaxValue(row[`formulaType${item.weightKey}`]).precision"
                      :max="getMaxValue(row[`formulaType${item.weightKey}`]).maxValue"
                      placeholder="请输入"
                      style="margin-right:4px;width: 100px;"
                    ></z-input-number>
                    {{ getFormulaTypeUnit(row[`formulaType${item.weightKey}`]).unit }}
                  </div>
                </div>
              </div>
            </template>
            <!-- <template #default="{ row }"></template> -->
          </z-table-column>
        </z-table>
      </template>
    </BasicCard>

    <!-- 选择目的地区域 -->
    <quoteDestination
      ref="areaGroupRef"
      :canSelectTypes="canSelectTypes"
      :defaultSelectType="defaultSelectType"
      :quoteBasicInfo="quoteBasicInfo"
      :isShowDestinationType="false"
      @confirmSelect="confirmRegionSelect"
    ></quoteDestination>
    <!-- 报价导入/上传 -->
    <import-dialog ref="importRef" :formData="formData" @success="handleImportSuccess"></import-dialog>
  </div>
</template>

<script>
import BasicCard from '@/views/pages/baseManagement/view/components/basicCard.vue'
import quoteDestination from '@/views/pages/feePolicyManage/components/quoteDestination/dialog.vue'
import { max, cloneDeep } from '@zto/z-utils-es'
import { descRegionTypeEnum } from '@/quoteComps/quoteConfig/option.js'
import { feeTypeEnum, feeModeOpts } from '@/views/pages/feePolicyManage/opts.js'
import { exportQuoteRules } from '@/api/policyRule/index.js'
import { downloadFile } from '@/utils'
import { formulaTypeOptions, getTableColumns, MAX_WEIGHT, MAX_PRICE, getUnitByFormulaType } from './config'
import { findSameElements, findDifference } from '../../utils'
import quickForm from './weightRange/quickForm.vue'
import { getDefaultProvince, handleTransferData } from './index'
import importDialog from './importSheet.vue'

export default {
  components: {
    BasicCard,
    quoteDestination,
    quickForm,
    importDialog
  },
  props: {
    editType: {
      type: String,
      default: 'edit' // edit:编辑模式，view：查看模式
    },
    // 报价基础信息
    formData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      feeTypeEnum,
      MAX_WEIGHT,
      MAX_PRICE,
      tableData: [
        {
          destinationAreaGroup: '默认',
          areaList: getDefaultProvince(),
          formula00: undefined, // 元/票
          formula10: undefined, // 元/kg
          formula20: undefined, // 浮动元/票
          formula30: undefined, // 重量
          formula40: undefined, // 元/kg
          formulaType0: '1' // 规则类型
        }
      ],
      tableColumns: [],
      dynamicColumns: [],
      minWeight: 0,
      canSelectTypes: [1],
      defaultSelectType: 1,
      quoteBasicInfo: {},
      regionType: descRegionTypeEnum.province,
      tempQuoteMode: '0',
      isEditTable: false,
      tableKey: Date.now() + Math.random()
    }
  },
  computed: {
    isEdit() {
      return this.editType === 'edit'
    },
    formulaTypeOpts() {
      // 中转费的时候返回feeMode
      const feeModeFilter = formulaTypeOptions.filter(item => item.feeModeBelongTo.includes(this.formData.subCostType))
      const data = feeModeFilter.filter(
        item => item.quoteModeBelongTo && item.quoteModeBelongTo.includes(this.formData.quoteMode)
      )
      const opts = [8].includes(this.formData.subCostType) ? feeModeFilter : data
      this.$nextTick(() => {
        const formulaType = opts && opts.length > 0 ? opts[0].value : '1'
        if (!this.isEditTable) {
          this.tableData[0].formulaType0 = formulaType
        }
      })
      return opts || []
    }
  },
  mounted() {
    const obj = getTableColumns(this)
    console.log(obj, this.formData)
    this.tableColumns = obj && obj.tableColumns ? obj.tableColumns : []
    this.dynamicColumns = obj && obj.dynamicColumns ? obj.dynamicColumns : []
  },
  methods: {
    getColMinValue(col, colIndex) {
      const nextItem = this.dynamicColumns[colIndex + 1]
      if (nextItem) {
        this.$set(this.dynamicColumns, 'startWeight', nextItem.startWeight)
        return nextItem.startWeight || this.minWeight
      }
      return this.minWeight
    },
    // 报价规则导出
    async handleExport() {
      // 校验必填
      const valid = await this.$parent.$parent.$parent.validForm()
      if (!valid) return
      // 获取数据
      const data = await this.$parent.$parent.$parent.getFormatData()
      const res = await exportQuoteRules(data)
      console.log(res, 'res')
      if (!res.status) return this.$message.error('导出失败!')
      downloadFile(res.result.filePath, `报价规则.xlsx`)
    },
    // 获取最大值，非固定和浮动模式
    getMaxValue(formulaType) {
      // 根据补收标准来判断
      const value = [feeTypeEnum.operate, feeTypeEnum.packageSurcharge].includes(this.formData.subCostType)
        ? this.formData.quoteMode
        : formulaType
      return feeModeOpts.find(item => item.value === value)
    },
    getFormulaTypeUnit(formulaType) {
      console.log(
        this.formulaTypeOpts.find(item => item.value === formulaType),
        ''
      )
      return this.formulaTypeOpts.find(item => item.value === formulaType)
    },
    // 校验目的组
    checkDestGroup(groups) {
      // 获取当前目的组数据
      const currentAreas = []

      groups.forEach(item => {
        const areaList = item.descNames.split(',').map((name, index) => ({
          label: name,
          id: Number(item.descCodes.split(',')[index])
        }))
        currentAreas.push(
          ...areaList.map(area => ({
            ...area
          }))
        )
      })
      // 获取全部目的组数据
      const findDifferenceData = findDifference(getDefaultProvince(), currentAreas, 'id')
      // 查找差集等于0表示包含全部目的组
      return {
        valid: findDifferenceData.length === 0,
        areaNames: findDifferenceData.map(item => item.label).join(',')
      }
    },
    validate() {
      // console.log(this.tableData, 'this.tableData')
      // 表单生成规则->formula00 第一个0代表的是规则类型，第二个0代表的是第几列
      return new Promise((resolve, reject) => {
        let hasError = false // 标记是否已经出现错误
        // 开始和结束重量段校验
        const weightRange = this.dynamicColumns.filter((item, index) => {
          // 开始重量不能大于等于结束重量，重量段连续
          const startWeight = item.startWeight
          const endWeight = item.endWeight
          // 重量段连续
          const nextItem = this.dynamicColumns[index + 1]
          return Number(startWeight) >= Number(endWeight) || (nextItem && item.endWeight !== nextItem.startWeight)
        })
        if (weightRange.length) {
          this.$message.error(`请检查重量段设置，开始重量段不能大于等于结束重量段，且必须连续！`)
          hasError = true
          reject(false) // 校验失败，返回错误信息
        }
        this.tableData.forEach(item => {
          if (hasError) return // 如果已经出现错误，则跳过当前项
          // 除了areaList destinationAreaGroup formulaType0外的所有字段
          const dyncamicKeys = this.dynamicColumns.map((el, index) => `formulaType${index}`)
          dyncamicKeys.forEach(key => {
            if (hasError) return // 如果已经出现错误，则跳过当前项
            const areaList = item.areaList
            const formulaTypeKeyIndex = key.split('formulaType')[1]
            const formulaTypeValue = item[key]

            const formula0Key = `formula0${formulaTypeKeyIndex}`
            const formula1Key = `formula1${formulaTypeKeyIndex}`
            const formula2Key = `formula2${formulaTypeKeyIndex}`
            const formula3Key = `formula3${formulaTypeKeyIndex}`
            const formula4Key = `formula4${formulaTypeKeyIndex}`
            if (!areaList.length) {
              this.$message.error(`区域组${item.destinationAreaGroup}的未配置目的地数据，请完善`)
              hasError = true
              reject(false) // 校验失败，返回错误信息
              return // 终止循环
            }
            // 等于1，只校验format10
            if (['1', '4'].includes(formulaTypeValue) && item[formula0Key] === undefined) {
              this.$message.error(`请检查${item.destinationAreaGroup}区域组的数据是否填写完整`)
              hasError = true
              reject(false) // 校验失败，返回错误信息
              // 终止循环
              return
            }
            if (formulaTypeValue === '2' && item[formula1Key] === undefined) {
              this.$message.error(`请检查${item.destinationAreaGroup}区域组的数据是否填写完整`)
              hasError = true
              reject(false) // 校验失败，返回错误信息
              return // 终止循环
            }
            if (
              formulaTypeValue === '3' &&
              (item[formula2Key] === undefined || item[formula3Key] === undefined || item[formula4Key] === undefined)
            ) {
              this.$message.error(`请检查${item.destinationAreaGroup}区域组的数据是否填写完整`)
              hasError = true
              reject(false) // 校验失败，返回错误信息
              // 终止循环
            }
          })
        })
        resolve(true) // 校验通过
      })
    },
    // 将数据组装成后端需要的数据
    getFormatData() {
      const ruleFormulas = []
      cloneDeep(this.dynamicColumns).forEach((item, index) => {
        cloneDeep(this.tableData).forEach((tableItem, tableIndex) => {
          // 获取key对应的索引 formulaType0 formulaType1 formulaType2
          const colIndex = item.weightKey
          const formulaTypeValue = tableItem[`formulaType${colIndex}`]
          const formulaUnit = this.getFormulaTypeUnit(formulaTypeValue)

          // console.log(formulaUnit, 'formulaUnit')
          const row = {
            subCostType: this.formData.subCostType, // 费用类型
            groupName: tableItem.destinationAreaGroup,
            groupIndex: tableIndex,
            startWeight: item.startWeight,
            endWeight: item.endWeight,
            oriRegionType: this.regionType, // 省
            descRegionType: this.regionType,
            descCodes: tableItem.areaList.map(el => el.value || el.id).join(','),
            descNames: tableItem.areaList.map(el => el.label).join(','),
            extendJsonFormat: [
              {
                item: formulaTypeValue === '3' ? 12 : 11, // 11 固定模式 12 续重模式
                baseWeight: undefined, // 首重（kg）
                itemUnit: formulaUnit.unitValue, // 首重/固定价单位
                itemValue: undefined, // 首重/固定价
                itemLabel: formulaUnit.unit,
                item2Unit: undefined, // 续重价单位
                item2Label: undefined,
                item2Value: undefined // 续重价
              }
            ]
          }
          // 重量模式
          // const unitEnum = {
          //   yuan: '0',
          //   yuanp: '1',
          //   yuankg: '2'
          // }

          switch (formulaTypeValue) {
            case '1':
              row.extendJsonFormat[0].itemValue = tableItem[`formula0${colIndex}`]
              break
            case '4':
              row.extendJsonFormat[0].itemValue = tableItem[`formula0${colIndex}`]
              break
            case '2':
              row.extendJsonFormat[0].itemValue = tableItem[`formula1${colIndex}`]
              break
            case '3':
              row.extendJsonFormat[0].baseWeight = tableItem[`formula3${colIndex}`]
              row.extendJsonFormat[0].itemValue = tableItem[`formula2${colIndex}`]
              row.extendJsonFormat[0].item2Value = tableItem[`formula4${colIndex}`]
              row.extendJsonFormat[0].item2Unit = getUnitByFormulaType('2').unitValue
              row.extendJsonFormat[0].item2Label = getUnitByFormulaType('2').unit
              break
            default:
              break
          }
          ruleFormulas.push(row)
        })
      })
      console.log(ruleFormulas, 'ruleFormulas')
      return ruleFormulas
    },
    setTableData(tableData, columns) {
      this.tableKey = Date.now() + Math.random()
      this.isEditTable = true
      this.tableData = cloneDeep(tableData)
      this.dynamicColumns = cloneDeep(columns)
    },
    // 导入成功
    handleImportSuccess(rules) {
      const { outputArray, columns } = handleTransferData(rules)
      // console.log(rules, 'rules')
      this.$nextTick(() => {
        this.setTableData(outputArray, columns)
      })
    },
    // 判断最后一行
    isLastRow(index) {
      return index === this.tableData.length - 1
    },
    handleBatchUpdate(quickForm) {
      // 获取输入的行数据（哪些行需要调整）
      const rowData = quickForm.groupName
      // 获取输入的列数据（哪些列需要调整）
      const columnData = quickForm.weightGroup
      console.log(rowData, columnData, 'rowData, columnData')
      let tempArr = this.tableData
      if (rowData && rowData.length) {
        // 找出需要调整的行数据
        tempArr = tempArr.filter(el => rowData.includes(el.destinationAreaGroup))
      }
      // 找出需要调整的列数据
      const columnArr = columnData && columnData.length ? columnData : this.dynamicColumns.map(el => el.weightKey)
      tempArr.forEach(item => {
        columnArr.forEach(el => {
          switch (quickForm.formulaType) {
            case '1':
              item[`formula0${el}`] = quickForm.formula
              break
            case '2':
              item[`formula1${el}`] = quickForm.formula1
              break
            case '3':
              item[`formula2${el}`] = quickForm.formula2
              item[`formula3${el}`] = quickForm.formula3
              item[`formula4${el}`] = quickForm.formula4
              break
            case '4':
              item[`formula0${el}`] = quickForm.formula
              break
          }
          item[`formulaType${el}`] = quickForm.formulaType
        })
      })
    },
    handleDelete(column) {
      const { startWeight, endWeight, weightKey } = column
      const index = this.dynamicColumns.findIndex(item => item.weightKey === weightKey)
      if (this.dynamicColumns.length === 1) return
      this.dynamicColumns.splice(index, 1)
      this.tableData.forEach(item => {
        delete item[`formula0${weightKey}`]
        delete item[`formula1${weightKey}`]
        delete item[`formula2${weightKey}`]
        delete item[`formula3${weightKey}`]
        delete item[`formula4${weightKey}`]
        delete item[`formulaType${weightKey}`]
      })
      if (index === 0) {
        // 如果删除的是第一个重量段，需要更新第二个重量段的开始值
        this.dynamicColumns[index].startWeight = startWeight
      } else {
        // 如果删除的是中间的重量段，需要更新前一个重量段的结束值
        this.dynamicColumns[index - 1].endWeight = endWeight
      }
    },
    handleWeightBlur(column) {
      this.tableKey = Date.now() + Math.random()
      const { startWeight, endWeight } = column
      const colLength = this.dynamicColumns.length
      // 结束重量段没有输入值不插入
      if (endWeight === undefined) return
      // 重量段超过20，不插入
      if (this.dynamicColumns.length >= 20) {
        // 最后一个重量段的值必须为999

        this.$set(this.dynamicColumns[colLength - 1], 'endWeight', MAX_WEIGHT)
        return this.$message.warning('最多只能添加20个重量段')
      }
      // 结束重量段必须小于小于999&不是最后一个重量段
      if (endWeight >= MAX_WEIGHT && this.dynamicColumns.length < 20)
        return this.$message.warning(`重量段的结束值必须是${MAX_WEIGHT}`)
      // 结束重量段必须大于开始重量段
      if (startWeight >= endWeight) return this.$message.warning('结束重量不能小于开始重量')

      const maxWeightKey = max(this.dynamicColumns.map(item => item.weightKey))
      const index = this.dynamicColumns.findIndex(item => item.weightKey === column.weightKey)
      // 向前插入一条数据
      const next = this.dynamicColumns[index + 1]
      // 从第一个拆和最后一个拆
      const newColumn = {
        startWeight: endWeight,
        endWeight: next ? next.startWeight : MAX_WEIGHT,
        weightKey: maxWeightKey + 1
      }
      // 值没有改，只是失去焦点不要拆
      if (next && endWeight === next.startWeight) {
        //  this.$message.warning('重量段无改动，不拆分重量段')
        return
      }
      // 从中间拆分重量段会出现这种情况,需要判断是否小于小一行的结束值，否则有误
      if (newColumn.startWeight > newColumn.endWeight) {
        // 修改当前重量段数据
        // 更新下一条重量段的值，确保在下一个段区间进行更改
        if (next.endWeight > endWeight) {
          next.startWeight = endWeight
          // 不需要插入了，直接跳出函数
          return
        }
        // if (newColumn.endWeight < next.startWeight) {
        // return this.$message.warning('结束重量不能大于等于下一个重量段的开始重量')
        // }
        // this.$set(this.dynamicColumns[index + 1], 'startWeight', endWeight)
      }
      this.dynamicColumns.splice(index + 1, 0, newColumn)

      console.log(this.dynamicColumns, 'this.dynamicColumns')

      // 重新更新表格数据字段属性
      // 更新表格数据字段属性
      this.tableData.forEach((item, index) => {
        const obj = {
          [`formula0${maxWeightKey + 1}`]: undefined,
          [`formula1${maxWeightKey + 1}`]: undefined,
          [`formula2${maxWeightKey + 1}`]: undefined,
          [`formula3${maxWeightKey + 1}`]: undefined,
          [`formula4${maxWeightKey + 1}`]: undefined,
          [`formulaType${maxWeightKey + 1}`]: this.formulaTypeOpts.length === 1 ? this.formulaTypeOpts[0]?.value : '1'
        }
        this.$set(this.tableData, index, {
          ...item,
          ...obj
        })
      })
    },
    // 新增区域组
    handleAddAreaGroup(index) {
      this.$refs.areaGroupRef.open(index, this.tableData, 'areaList', 'add')
    },
    // 编辑区域组
    handleEditAreaGroup(index) {
      this.$refs.areaGroupRef.open(index, this.tableData, 'areaList', 'edit')
    },
    // 处理重合省份
    handleOverlapProvince(dataList, index, editType) {
      const tableData = cloneDeep(this.tableData)
      const affectedGroups = []
      const tempDataList = cloneDeep(dataList).map(item => ({ ...item, id: Number(item.id) }))
      tableData.forEach((item, i) => {
        // 找出重合的省份
        const overlappingProvinces = findSameElements(
          item.areaList.map(item => ({ ...item, id: Number(item.id) })),
          tempDataList,
          'id'
        )
        // 跳过当前正在编辑的区域组
        if (i === index && editType !== 'add') {
          // 把添加加到当前组里面取
          tableData[i].areaList = tempDataList
          return
        }

        if (overlappingProvinces.length > 0) {
          // 从原有区域组中移除重合的省份
          const newAreaList = findDifference(
            item.areaList.map(item => ({ ...item, id: Number(item.id) })),
            overlappingProvinces,
            'id'
          )

          // 记录受影响的区域组
          affectedGroups.push({
            groupName: item.destinationAreaGroup,
            removedProvinces: overlappingProvinces.map(p => p.label).join('、'),
            remainingCount: newAreaList.length
          })

          // 更新区域组数据
          tableData[i].areaList = newAreaList

          // // 如果移除重合省份后该组为空，则删除该组（排除默认组）再此不要更新
          // if (newAreaList.length === 0 && item.destinationAreaGroup !== '默认') {
          //   // this.handleDeleteAreaGroup(i)
          //   tableData.splice(i, 1)
          // }
        }
      })
      return {
        affectedGroups,
        tableData
      }
    },
    // 判断是否是默认分组
    isDefaultGroup(item) {
      return item.destinationAreaGroup === '默认'
    },
    updateAreaGroupData() {
      // 查找所有行的数据，除了默认分组
      let noDefaultData = []
      this.tableData
        .filter(item => !this.isDefaultGroup(item))
        .forEach(item => {
          noDefaultData.push(...item.areaList)
        })
      noDefaultData = noDefaultData.map(item => ({ ...item, id: Number(item.id) }))
      const findDifferenceData = findDifference(getDefaultProvince(), noDefaultData, 'id')
      const index = this.tableData.findIndex(item => item.destinationAreaGroup === '默认')
      this.$set(this.tableData[index], 'areaList', findDifferenceData)
    },
    /**
     * 确认目的地选择
     * @param {Object} params 参数对象
     * @param {Array} params.dataList 选择完目的地数据
     * @param {number} params.regionType 目的地类型
     * @param {Object} params.formData 表单数据
     * @param {string} params.editType 编辑类型
     * @param {number} params.index 当前编辑的表格的索引
     */
    confirmRegionSelect({ dataList, regionType, formData, editType, index }) {
      // 参数验证
      if (!Array.isArray(dataList)) {
        this.$message.error('数据格式错误：dataList必须是数组')
        return
      }
      // 处理空数据列表的情况，不处理有区域组&数据为空情况，可能是删除操作
      if (dataList.length === 0 && !this.isDefaultGroup(this.tableData[index])) {
        this.handleDeleteAreaGroup(index)
        return
      }
      // 校验区域组是否重复
      const hasSameGroup = this.tableData.some(
        (item, rowIndex) =>
          item.destinationAreaGroup === formData.destinationName && (editType === 'add' ? true : rowIndex !== index)
      )
      if (hasSameGroup) {
        this.$message.error('目的地区域组已存在')
        return
      }

      // 处理重合省份
      const { affectedGroups, tableData } = this.handleOverlapProvince(dataList, index, editType)

      // 更新区域组数据
      const updateAreaGroup = () => {
        const tempData = cloneDeep(tableData)
        let newGroupData = {
          destinationAreaGroup: formData.destinationName,
          areaList: dataList
        }

        if (editType === 'edit') {
          newGroupData = {
            ...tempData[index],
            ...newGroupData
          }
          tempData[index] = newGroupData
          this.tableData = tempData.filter(item => item.areaList.length > 0)
          return
        }

        // // 检查重复区域组
        // const hasSameGroup = this.tableData.some(item => item.destinationAreaGroup === formData.destinationName)
        // if (hasSameGroup) {
        //   this.$message.error('目的地区域组已存在')
        //   return
        // }
        // 添加新区域组 需要获取当前行的字段
        let obj = {}
        this.dynamicColumns.forEach(item => {
          obj = {
            ...obj,
            [`formula0${item.weightKey}`]: undefined,
            [`formula1${item.weightKey}`]: undefined,
            [`formula2${item.weightKey}`]: undefined,
            [`formula3${item.weightKey}`]: undefined,
            [`formula4${item.weightKey}`]: undefined,
            [`formulaType${item.weightKey}`]: this.formulaTypeOpts.length === 1 ? this.formulaTypeOpts[0]?.value : '1'
          }
        })
        console.log(obj, 'obj')
        newGroupData = {
          ...newGroupData,
          ...obj
        }

        // 添加新区域组
        tempData.push(newGroupData)
        this.tableData = tempData.filter(item => item.areaList.length > 0)
        console.log(this.tableData, tempData, 'this.tableData')
      }
      // 过滤默认省份
      const noDeaultAffectedGroups = affectedGroups.filter(group => group.groupName !== '默认')
      // 如果有受影响的区域组，显示确认对话框
      if (noDeaultAffectedGroups.length > 0) {
        const message = noDeaultAffectedGroups
          .map(group => {
            const action = group.remainingCount === 0 ? '已清空' : `剩余${group.remainingCount}个地区`
            return `区域组${group.groupName}：移除省份${group.removedProvinces}，${action}<br />`
          })
          .join('\n')

        this.$confirm(`确认后，将更新以下区域组的目的地：<br />${message}<br />请确认是否更新？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning',
          showClose: false
        })
          .then(() => {
            // this.tableData = tableData
            updateAreaGroup()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
      } else {
        updateAreaGroup()
      }

      // 更新默认省份数据
      this.updateAreaGroupData()
    },
    // 删除区域组
    handleDeleteAreaGroup(index) {
      const { destinationAreaGroup } = this.tableData[index]
      this.$confirm(`确认要删除${destinationAreaGroup}区域组吗？删除后，数据将不能恢复！`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false
      })
        .then(() => {
          // 查找所有行的数据默认分组
          let noDefaultData = []
          this.tableData
            .filter((item, rowIndex) => !this.isDefaultGroup(item) && index !== rowIndex)
            .forEach(item => {
              noDefaultData.push(...item.areaList)
            })
          noDefaultData = noDefaultData.map(item => ({ ...item, id: Number(item.id) }))
          const findDifferenceData = findDifference(getDefaultProvince(), noDefaultData, 'id')
          this.$set(this.tableData[0], 'areaList', findDifferenceData)
          this.tableData.splice(index, 1)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 导入报价
    handleImport() {
      this.$refs.importRef.open()
    },
    getMinWidth(item) {
      return this.tableData.some(row => row[`formulaType${item.weightKey}`] === '3') ? '460px' : '220px'

      // return row[`formulaType${item.weightKey}`] === '3' ? '460px' : '120px'
    }
  }
}
</script>
<style lang="scss" scoped>
.page-flex {
  .page-flex-footer {
    background-color: #fff;
    padding: 12px 0;
    text-align: center;
  }
  .z-icon-delete {
    font-size: 16px;
    margin-left: 3px;
  }
}
.z-tag {
  margin-right: 8px;
}
.fill-form-item {
  width: 100%;
}
.package-mode {
  margin-bottom: 8px;
}
.page-container {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  padding: 16px;
  .actions {
    align-items: center;
    display: flex;
  }
}
.flex-box {
  display: flex;
  position: relative;
  .flex-box__item {
    left: 4px;
    position: absolute;
    top: 0;
    ::v-deep .z-input__inner {
      height: 24px;
      line-height: 24px;
    }
  }
}
.area-box {
  align-items: center;
  display: flex;
  .group-name {
    display: inline-block;
    max-width: 100px;
  }
  .area-list {
    flex: 1;
    .desination {
      background-color: #e5e9f2;
      border-radius: 4px;
      display: inline-block;
      margin: 4px 0 2px 8px;
      padding: 0 4px;
    }
    i {
      font-size: 16px;
      margin-left: 10px;
    }
  }
  .z-icon-circle-plus-outline {
    color: #3693ff;
  }
  .z-icon-delete {
    color: #ed4014;
  }
}
::v-deep {
  .header-box {
    align-items: center;
    display: flex;

    .z-input-number {
      width: 70px;
    }
  }
}
.fastSet-box {
  background: #fafafa;
  border-radius: 4px;
  box-sizing: border-box;
  display: flex;
  margin-bottom: 10px;
  padding: 0 0 0 8px;
  .form-box {
    flex: 1;
  }
  .form-title {
    color: #3693ff;
    font-size: 16px;
    margin: 10px 16px 0 0;
    width: 32px;
  }
  .z-form {
    margin-top: 8px;
    .form-item-box {
      margin-left: 24px;
      margin-top: 24px;
    }
  }
  ::v-deep .z-form-item__label {
    display: block;
    line-height: 24px;
    text-align: left;
  }
}
</style>
